package com.example.testsystem;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.LocalOnlyHotspotReservation;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.widget.Toast;
import android.content.pm.PackageManager;

public class WifiActivity extends Activity {
    private static final String TAG = "TestSystemWifiActivity";
    private Button btnStopsoftap;
    private Button btnStartTethering;
    private Button btnStartLocalHostSpot;
    private Context mContext = this;
    private WifiManager wifiManager;
    private static final int REQUEST_CODE_PERMISSIONS = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi); //important, 遇到忘记修改这儿，导致crash
        wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        // 检查并请求权限
        if (checkPermissions()) {
            Log.d(TAG, "权限已被授予");
            // 权限已经被授予
            Toast.makeText(this, "权限已被授予", Toast.LENGTH_SHORT).show();
        } else {
            // 权限没有被授予，请求权限
            Log.d(TAG, "权限未被授予，请求权限");
            requestPermissions();
        }

        btnStopsoftap = findViewById(R.id.btn_stopsoftap);
        btnStopsoftap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "btnStopsoftap click...");
                wifiManager.stopSoftAp();
                boolean ret = wifiManager.stopSoftAp();
                Log.i(TAG, "stopSoftAp ret = " + ret);
            }
        });

        btnStartTethering = findViewById(R.id.btn_starttethering);
        btnStartTethering.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "btnStartTethering click...");
                boolean ret = wifiManager.startTetheredHotspot(null);
                Log.i(TAG, "startTetheredHotspot ret = " + ret);
            }
        });

        btnStartLocalHostSpot = findViewById(R.id.btn_startlocalhostspot);
        btnStartTethering.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openLocalHostSpot();
            }
        });
    }

    private void openLocalHostSpot() {
        wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
            @Override
            public void onStarted(LocalOnlyHotspotReservation reservation) {
                super.onStarted(reservation);
                //mLocalOnlyHotspotReservation = reservation;
                String ssid = reservation.getWifiConfiguration().SSID;
                String pwd = reservation.getWifiConfiguration().preSharedKey;
                Log.e(TAG, "ssid and pwd is" + ssid + "and" + pwd);
                Log.i(TAG, "softap ssid = " + reservation.getSoftApConfiguration().getSsid() + " psk = " + reservation.getSoftApConfiguration().getPassphrase());
                //HandlerThread testHandlerThread = new HandlerThread(reservation);
            }

            @Override
            public void onStopped() {
                super.onStopped();
                Log.e("SetLocalOnlyHotSpotController", "stopped");
            }

            @Override
            public void onFailed(int reason) {
                super.onFailed(reason);
            }
        }, new Handler());
    }

    // 检查权限是否已授予
    private boolean checkPermissions() {
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this,
                Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    // 请求权限
    private void requestPermissions() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CHANGE_WIFI_STATE,
                        Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_CODE_PERMISSIONS);
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            // 检查每个权限的授权情况
            boolean allPermissionsGranted = true;
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                Toast.makeText(this, "所有权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "部分权限未授予", Toast.LENGTH_SHORT).show();
            }
        }
    }
}